define(["utils"], function (utils) {
    function pageLogic(config) {
        this.pageview = config.pageview;
        this.dropdownTempalteID = null;
        this.curTableHeaderTempalteID = "1";
        this.choiceAll = false;
        this.params = {};
        this.index = 1; //页数
        this.selectedRowsArry = []; //选中行
    }

    var defaultColumns = [
        {
            headerText: "提交时间",
            cell: ["row_checkbox", "row_submittime"],
            headerStyle: {
                width: 110
            }

        },
        {
            headerText: "提交人",
            cell: ["row_creator"],
            headerStyle: {
                width: 110
            }
        }

    ];
    pageLogic.prototype = {
        table_didmount: function (sender) {
            // sender.loadPageDataByIndex(1);
        },
        main_body_init: function (sender) {
            this.main_body = sender;
        },
        seach_tem_dropdown_init: function (sender) {
            this.seach_tem_dropdown = sender;
        },
        table_init: function (sender, params) {
            this.table = sender;
        },
        row_checkbox_didmount: function (sender) {
            for (var i = 0; i < this.selectedRowsArry.length; i++) {
                if (this.selectedRowsArry[i].datasource.id === sender.datasource.id) {
                    this.setC(sender);
                }
            }
        },
        setC: function (sender) {
            window.setTimeout(function () {
                sender.rowInstance.select();
            }, 100);
        },
        seach_tem_dropdown_getdata: function (sender, params) {
            this.dropdown_getdata(params, this.choiceAll);
        },
        table_afterbinddata: function (sender, params) {
            var _this = this;
            window.setTimeout(function () {
                if (_this.table.rows.length === _this.table.selectedRows.length) {
                    _this.checkbox_all.selected();
                }
            }, 300);
        },
        dropdown_getdata: function (params, isAll) {
            var client = isAll ? "web" : "select";
            this.pageview.ajax({
                type: "GET",
                url: "/template/list",
                data: {
                    pageNumber: 1,
                    pageSize: 1000,
                    client: client
                },
                success: function (data) {
                    if (data.code === 0) {
                        if (client === "select") {
                            params.success(data.data);
                        }
                        else {
                            //数据结构不一样,做适配处理
                            params.success(data.data.list);
                        }

                    } else {
                        params.error();
                    }
                }, error: function () {
                    params.error();
                }
            });
        },
        seach_tem_dropdown_change: function () {

        },
        tablenodata_init: function (sender) {
            this.tablenodata = sender;
        },
        table_parsedata: function (sender, params) {
            var data = params.data;

            var totalPages = 0;
            if (data.code !== 0) {
                return false;
            }
            if (data.data === "") {
                data = [];
            } else {
                data = data.data.list;
                // data = data.data;
                totalPages = params.data.data.pages;
            }
            if (data.length === 0) {
                this.tablenodata.$el.removeClass("displaynone");
                this.pageview.refs.count_tips.$el.addClass("displaynone");
                this.pageview.refs.bottom_btn_wrap.$el.addClass("displaynone");
                this.pageview.refs.paginator.$el.addClass("displaynone");
                // this.main_body.$el.addClass("displaynone");
            }
            var idDict = {};
            for (var i = 0, j = data.length; i < j; i++) {
                var rowData = data[i];
                // rowData.content[0]="'";
                // rowData.content[rowData.content.length-1]="'";
                var content = rowData.content.replace(/\t/g, '  ');
                var contentObj;
                // this.main_body.$el.removeClass("displaynone");
                this.pageview.refs.count_tips.$el.removeClass("displaynone");
                this.pageview.refs.bottom_btn_wrap.$el.removeClass("displaynone");
                this.pageview.refs.paginator.$el.removeClass("displaynone");
                this.tablenodata.$el.addClass("displaynone");
                rowData.sendTime = utils.ConvertDateToStr(rowData.createTime, "MM-dd hh:mm");
                try {
                    contentObj = JSON.parse(content);
                } catch (e) {
                    this.pageview.showTip({"text": "模版内容结构解析失败!"});
                }

                for (var ii = 0, jj = contentObj.length; ii < jj; ii++) {
                    var itemContent = contentObj[ii].content;
                    if (!idDict[ii.toString()]) {
                        idDict[ii.toString()] = new Date().getTime() + ii;


                    }
                    console.log(idDict[ii.toString()]);
                    contentObj[ii].id = idDict[ii.toString()];
                    rowData[idDict[ii.toString()]] = itemContent;
                }
                data[i].content = JSON.stringify(contentObj);
            }
            this.createHeader(data[0], sender);

            return {data: data, pageCount: totalPages};
        },
        createHeader: function (rowData, sender) {
            if (!rowData) {
                sender.createHeader([]);
                return;
            }
            var content = rowData.content;
            var contentObj;
            try {
                contentObj = JSON.parse(content);
            } catch (e) {
                this.pageview.showTip({"text": "模版内容结构解析失败!"});
            }
            // if(this.curTableHeaderTempalteID!==this.dropdownTempalteID){
            this.curTableHeaderTempalteID = this.dropdownTempalteID;
            var columns = utils.copy(defaultColumns);

            for (var i = 0, j = contentObj.length; i < j; i++) {
                var itemData = contentObj[i];
                var rowWidth = 220;
                if (itemData.type === "InputDate" || itemData.type === "InputCheckbox" || itemData.type === "InputRadio" || itemData.type === "InputTextNum") {
                    //当这列的类型是数字、单选、多选、日期时,宽度给100
                    rowWidth = 110;
                }
                //itemData.id=new Date().getTime();
                var com_key = "text_" + itemData.id;
                columns.push({
                    headerText: itemData.title,
                    cell: [com_key],
                    headerStyle: {
                        width: rowWidth
                    }

                });
                this.pageview.config.components[com_key] = {
                    type: "text",
                    style: {
                        maxHeight: "100px"
                    },
                    text_bind: itemData.id.toString()
                };
            }
            columns.push({
                headerText: "",
                cell: []
            });
            sender.createHeader(columns);
            // }
        },

        add_range_icon_click: function (sender) {
            this.pageview.refs.personSelector.show(this.templateVisibleRange);
        },
        range_title_click: function () {
            this.pageview.refs.personSelector.show(this.templateVisibleRange);
        },
        personSelector_ok: function (sender, params) {
            var selectedData = sender.selectedData;
            this.templateVisibleRange = selectedData;
            var Re = [];
            for (var i = 0, j = this.templateVisibleRange.length; i < j; i++) {
                Re.push(this.templateVisibleRange[i].userName || this.templateVisibleRange[i].teamName);
            }

            if (Re.length === 0) {
                this.pageview.refs.range_title.setText("选择提交人");
                this.pageview.refs.range_title.$el.css({color: "#aaa"});
            } else {
                this.pageview.refs.range_title.setText(Re.join(","));
                this.pageview.refs.range_title.$el.css({color: "#333"});
            }
            // this.pageview.delegate("tips_repeat",function(target){
            //   target.bindData(selectedData);
            // });


            this.pageview.refs.personSelector.hide();
        },
        table_rowclick: function (sender) {
            sender.select();
            if (sender.isSelected) {
                this.row_select(sender);
            }
            else {
                this.row_unSelect(sender);
            }
        },
        row_select: function (sender) {
            //选中一行放入数组并更新提示
            var id = sender.datasource.id;
            for (var i = 0; i < this.selectedRowsArry.length; i++) {
                if (this.selectedRowsArry[i].datasource.id === id) {
                    return;
                }
            }
            //如果已选中当前页面所有行,则选中全选按钮
            if (this.table.rows.length === this.table.selectedRows.length) {
                this.checkbox_all.selected();
            }
            this.selectedRowsArry.push(sender);
            this.count_tips.setText("已选中<span style='color:#1FDA9A'>" + this.selectedRowsArry.length + "</span>份日志");
        },
        row_unSelect: function (sender) {
            //取消选中的一行并更新提示
            var id = sender.datasource.id;
            for (var i = this.selectedRowsArry.length - 1; i >= 0; i--) {
                if (this.selectedRowsArry[i].datasource.id === id) {
                    this.selectedRowsArry.splice(i, 1);
                }
            }
            this.checkbox_all.unSelected();
            this.count_tips.setText("已选中<span style='color:#1FDA9A'>" + this.selectedRowsArry.length + "</span>份日志");
        },
        checkbox_all_init: function (sender, params) {
            this.checkbox_all = sender;
        },
        checkbox_all_click: function (sender, params) {
            if (sender.value) {
                this.table.clearSelectAll();
                for (var i = this.table.rows.length - 1; i >= 0; i--) {
                    this.row_unSelect(this.table.rows[i]);
                }
                sender.unSelected();
            }

            else {
                this.table.selectAll();
                for (var ii = 0; ii < this.table.rows.length; ii++) {
                    this.row_select(this.table.rows[ii]);
                }
                sender.selected();
            }
        },
        count_tips_init: function (sender, params) {
            this.count_tips = sender;
            sender.config.noHoverTitle = true;
            sender.config.text = "已选中<span style='color:#1FDA9A'>" + this.selectedRowsArry.length + "</span>份日志";
        },
        search_checkbox_click: function (sender, params) {
            this.seach_tem_dropdown.hasBinData = false;
            if (sender.value) {
                //只显示启用的模板
                this.choiceAll = false;
                sender.unSelected();
            }
            else {
                //显示所有模板
                this.choiceAll = true;
                sender.selected();
            }
        },
        search_nameinput_change: function (sender, params) {
            this.pageview.ajax({
                // url: this.pageview.pageManager.appConfig.signInHost + "/dept/searchUser",
                url: "/team/searchUser",
                type: "GET",
                data: {
                    userName: params.value
                },
                success: function (data) {
                    if (data.code === 0) {
                        data = data.data;

                        var processData = [];

                        for (var i = 0; i < data.length; i++) {
                            processData.push({
                                id: data[i].id,
                                value: data[i].userName
                            });
                        }
                        params.success(processData);
                    }
                }, error: function (e) {

                }
            });
        },
        search_starttime_init:function(sender, params){
            //开始时间默认向前推15天
            var today = new Date();
            var startDay = new Date(today.getTime() - 15*24*60*60*1000);
            sender.config.value = startDay;
        },
        search_starttime_change: function (sender, params) {
            var endDate = this.pageview.refs.search_endtime.getValue();
            if (endDate.date === undefined) {
                this.pageview.refs.search_endtime.setValue(params.date);
            } else {
                if (utils.compareDate(params.date, endDate.date) === 1) {
                    this.pageview.refs.search_endtime.setValue(params.date);
                }
            }
        },
        search_endtime_change: function (sender, params) {
            var startDate = this.pageview.refs.search_starttime.getValue();
            if (startDate.date === undefined) {
                this.pageview.refs.search_starttime.setValue(params.date);
            } else {
                if (utils.compareDate(startDate.date, params.date) === 1) {
                    this.pageview.refs.search_starttime.setValue(params.date);
                }
            }
        },
        search_btn_click: function (sender) {
            var _this = this;
            var userIds = [];
            var teamIds = [];
            var deptIds = [];

            this.templateVisibleRange = this.templateVisibleRange || [];
            for (var i = 0, j = this.templateVisibleRange.length; i < j; i++) {
                var itemData = this.templateVisibleRange[i];
                if (itemData.dataType === 1) {//部门
                    deptIds.push(itemData.teamId);
                }
                if (itemData.dataType === 4) {
                    userIds.push(itemData.memberId);
                }
                if (itemData.dataType === 3) {
                    teamIds.push(itemData.teamId);
                }
            }


            var templateId = this.pageview.refs.seach_tem_dropdown.valueData.id;
            var startDate = this.pageview.refs.search_starttime.selectedValueStr;
            var endDate = this.pageview.refs.search_endtime.selectedValueStr;
            this.dropdownTempalteID = templateId;
            if (!this.pageview.refs.seach_tem_dropdown.hasBinData && this.pageview.refs.seach_tem_dropdown.valueData.title === "选择模板") {
                this.pageview.showTip({
                    text: "请选择模板",
                    duration: 1000
                });
                return;
            }
            this.pageview.refs.table.setAjaxConfigParams({
                userIds: userIds.join(","),
                deptIds: deptIds.join(","),
                teamIds: teamIds.join(","),
                templateId: templateId,
                beginDate: startDate,
                endDate: endDate,
                pageSize: 20
            });
            this.pageview.refs.table.loadPageDataByIndex(1);
            this.selectedArry_reset();
            // this.pageview.ajax({
            // 	url: "/diaryQuery/getDiaryStatistics",
            // 	type: "GET",
            // 	data: _this.params,
            // 	success: function (data) {
            // 		if (data.code === 0) {
            //
            // 		}
            // 	}, error: function (e) {
            //
            // 	}
            // });
        },
        paginator_change: function (sender, params) {
            this.checkbox_all.unSelected();
            this.table.selectedRows = [];
        },
        selectedArry_reset: function () {
            this.checkbox_all.unSelected();
            this.selectedRowsArry = [];
            this.count_tips.setText("已选中<span style='color:#1FDA9A'>0</span>份日志");
        },
        excel_btn_click: function (sender, params) {
            var _this = this;
            var token = this.pageview.params.token;
            var id = this.pageview.refs.seach_tem_dropdown.valueData.id;
            var url = "/diaryQuery/exportDiaryStatistics?timestamp=" + (new Date()).valueOf() + "&token=" + token + "&templateId=" + id;
            url = utils.getUrl(url);
            window.open(url);
            // this.pageview.showSubmiting({successText:null,text:"正在处理中..."});
            // this.pageview.ajax({
            // 	type: "GET",
            // 	url: "/diaryQuery/exportDiaryStatistics",
            // 	data: {
            // 		templateId:_this.pageview.refs.seach_tem_dropdown.valueData.id
            // 	},
            // 	success: function (data) {
            // 		if (data.code === 0) {
            // 			_this.pageview.hideSubmiting(data.code === 0);
            // 		}
            // 	}, error: function () {
            // 		_this.pageview.hideSubmiting(false);
            // 	}
            // });
        },
        summary_btn_click: function (sender, params) {
            //点击汇总日志按钮
            var _this = this;
            if (this.selectedRowsArry.length === 0) {
                this.pageview.showTip({
                    text: "请选择汇总的日志",
                    duration: 1000
                });
                return;
            }
            this.pageview.showPage({
                pageKey: "add",
                mode: "slide",
                params: {
                    summaryData: _this.selectedRowsArry,
                    isSummary: true,
                    templateData: _this.pageview.refs.seach_tem_dropdown.valueData
                }
            });
        },
    };
    return pageLogic;
});
